var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var geocoder;
var layer;
var tour;
var waypts;
var lastWindow;
var nbhdtable = 610444;
var poitable = 610420;
var poilayer = new google.maps.FusionTablesLayer(poitable);

function initialize() {
    geocoder = new google.maps.Geocoder();
    var styles = [
	{
	    featureType: "poi.attraction",
	    elementType: "geometry",
	    stylers: [
		{ visibility: 'on' },
		{ hue: "#ff0000" },
		{ lightness: -50 },
		{ saturation: 100 }
	    ]
	},
	{
	    featureType: "poi.park",
	    elementType: "geometry",
	    stylers: [
		{ lightness: -50 },
		{ saturation:50 }
	    ]
	},
	{
	    featureType: "water",
	    elementType: "geometry",
	    stylers: [
		{ hue: "#0000ff" },
		{ lightness: -50 }
	    ]
	}
    ];
    directionsDisplay = new google.maps.DirectionsRenderer({
	suppressMarkers: true,
	suppressInfoWindows: true});
    moscone = new google.maps.LatLng(37.7833365,-122.4026377);
    hyde = new google.maps.LatLng(37.806901,-122.421108);
    gg = new google.maps.LatLng(37.807231,-122.475241);
    haight = new google.maps.LatLng(37.769920,-122.446870);
    sunset = new google.maps.LatLng(37.771420,-122.510700);
    start = [moscone, hyde, haight ];
    end = [moscone, gg, sunset ];
    grace = new google.maps.LatLng(37.791847, -122.412891);   // 1100 California St
    coit= new google.maps.LatLng(37.8028181, -122.4058359);  // 1 Telegraph Hill Blvd
    ferry = new google.maps.LatLng(37.7955, -122.3937);
    wharf = new google.maps.LatLng(37.808333, -122.415556);
    sfmoma = new google.maps.LatLng(37.7855749, -122.4009522);  // 151 Third Street
    var myOptions = {
	zoom:12,
	mapTypeControl: false,
	mapTypeId: google.maps.MapTypeId.ROADMAP,
	center: moscone
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    var styledMapOptions = {
	name: "tourist"
    }
    var SFMapType = new google.maps.StyledMapType(styles, styledMapOptions);
    map.mapTypes.set('tourist', SFMapType);
    map.setMapTypeId('tourist');
    // neighborhood layer
    layer = new google.maps.FusionTablesLayer(nbhdtable);
    layer.setQuery("SELECT 'geometry' FROM " + nbhdtable);
    layer.setMap(null);
    ChangeTour(0);
    // Points of interest
    setData();
    // directions
    google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
	computeTotalDistance(directionsDisplay.directions);
    });
   //directionsDisplay.setMap(map);
    //calcRoute();
    hide_address_bar();
    var CustomText = '<input type="button" value="Neighborhoods" onclick="ToggleNeighborhoods();"></input><br><span id="total"></span>'
    var customControlDiv = document.createElement('DIV');
    var customControl = new LegendControl(customControlDiv, CustomText, map);
    customControlDiv.index = 1;
    map.controls[google.maps.ControlPosition.RIGHT_TOP].push(customControlDiv);
}

function setData() {
  //create a viz query to send to Fusion Tables
  var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + encodeURIComponent("SELECT Name, Location, icon, Number FROM 610420"));
  
  //set the callback function that will be called when the query returns
  query.send(getData);
}

//define callback function, this is called when the results are returned
function getData(response) {

  //for more information on the response object, see the documentation
  //http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
  numRows = response.getDataTable().getNumberOfRows();
  numCols = response.getDataTable().getNumberOfColumns();

  //create an array of row values
  for (i = 0; i < numRows; i++) {
    var row = [];
    for (j = 0; j < numCols; j++) {
      row.push(response.getDataTable().getValue(i, j));
    }
    codeAddress(row);
  }
    directionsDisplay.setMap(map);
    calcRoute();
}

/* GEOCODING - geocode data in Fusion Tables, if the data is a String Address */

//geocode the address, and create a new marker and InfoWindow at the geocoded location
function codeAddress(row) {
  geocoder.geocode( { 'address': row[1] }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
	var coordinate = results[0].geometry.location;

      //create the marker
      var marker = new google.maps.Marker({
          map: map, 
          position: coordinate,
          //this is where the magic happens!
          icon: new google.maps.MarkerImage(row[2])
      });
      
	if (Number(row[3]) == Number(tour)) {
	    waypts.push({location: coordinate, stopover: true})
	}

      //add a click listener to the marker to open an InfoWindow,
      google.maps.event.addListener(marker, 'click', function(event) {
        if(lastWindow) lastWindow.close(); //close the last window if it exists
        lastWindow = new google.maps.InfoWindow( {
          position: coordinate,
          content: row[0] + "<br />" + row[1]
        });
        lastWindow.open(map);
      });
    } 
  });
}

function ChangeTour(tourno) {
    tour = tourno;
    if (tour==0) {
    waypts = [{location: ferry, stopover: true},
	      {location: wharf, stopover: true},
	      {location:grace, stopover: true},
	      {location:sfmoma, stopover: true},
	      {location:coit, stopover: true}]
    } else {waypts = [];}
    setData();
    directionsDisplay.setMap(map);
    calcRoute();
}

function LegendControl(controlDiv, LegendText, map) {
    
    // Set CSS styles for the DIV containing the control
    // Setting padding to 5 px will offset the control
    // from the edge of the map
    controlDiv.style.padding = '5px';
    
    // Set CSS for the control border
    var controlUI = document.createElement('DIV');
    controlUI.style.backgroundColor = 'white';
    //controlUI.style.borderStyle = 'solid';
    //controlUI.style.borderWidth = '2px';
    controlUI.style.cursor = 'pointer';
    controlUI.style.textAlign = 'left';
    // controlUI.title = 'legend';
    controlDiv.appendChild(controlUI);
    
    // Set CSS for the control interior
    var controlText = document.createElement('DIV');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '12px';
    controlText.style.paddingLeft = '4px';
    controlText.style.paddingRight = '4px';
    controlText.innerHTML = LegendText;
    controlUI.appendChild(controlText);
    
}

function ToggleNeighborhoods() {
    if (layer.getMap()) {
	layer.setMap(null);
    } else {
	layer.setMap(map);
    }
}

function hide_address_bar () {
    setTimeout(function () {
	window.scrollTo(0, 1);
    }, 1);
}

function calcRoute() {
    // var start = document.getElementById("start").value;
    // var end = document.getElementById("end").value;
    //ferry = new google.maps.LatLng(37.7955, -122.3937);
    //wharf = new google.maps.LatLng(37.808333, -122.415556);
    //sfmoma = new google.maps.LatLng(37.7855749, -122.4009522);  // 151 Third Street
    //geocoder.geocode( { 'address': '151 Third Street, San Francisco, CA'}, function(results, status) {
    //if (status == google.maps.GeocoderStatus.OK) {
    //sfmoma = new google.maps.LatLng(results[0].geometry.location);
    //} else {
    //alert("Geocode was not successful for the following reason: " + status);
    //}
    //})
    //coit= new google.maps.LatLng(37.8028181, -122.4058359);  // 1 Telegraph Hill Blvd
    var request = {
        origin:start[tour],
        destination:end[tour],
	waypoints: waypts,
	optimizeWaypoints: true,
        travelMode: google.maps.DirectionsTravelMode.WALKING
    };
    directionsService.route(request, function(response, status) {
	if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
	}
    });
}

// http://code.google.com/apis/maps/documentation/javascript/examples/directions-draggable.html
function computeTotalDistance(result) {
    var total = 0;
    var myroute = result.routes[0];
    for (i = 0; i < myroute.legs.length; i++) {
      total += myroute.legs[i].distance.value;
    }
    total = total / 1609
    document.getElementById("total").innerHTML = "Distance: " + total.toFixed(1) + " miles";
  }
